import 'program_block.dart';

/// 程序模型类，用于存储和管理用户创建的程序
class Program {
  String name;
  List<ProgramBlock> startBlocks = []; // 程序的起始块列表（可能有多个事件触发点）
  
  Program({
    this.name = '未命名程序',
  });
  
  // 添加起始块
  void addStartBlock(ProgramBlock block) {
    if (block.type == BlockType.event) {
      startBlocks.add(block);
    }
  }
  
  // 移除起始块
  void removeStartBlock(ProgramBlock block) {
    startBlocks.remove(block);
  }
  
  // 清空程序
  void clear() {
    startBlocks.clear();
  }
  
  // 将程序转换为JSON格式（用于保存）
  Map<String, dynamic> toJson() {
    return {
      'name': name,
      'startBlocks': startBlocks.map(_blockToJson).toList(),
    };
  }
  
  // 从JSON格式加载程序
  static Program fromJson(Map<String, dynamic> json) {
    final program = Program(name: json['name']);
    
    for (var blockJson in json['startBlocks']) {
      program.startBlocks.add(_blockFromJson(blockJson));
    }
    
    return program;
  }
  
  // 将单个块转换为JSON
  static Map<String, dynamic> _blockToJson(ProgramBlock block) {
    final Map<String, dynamic> json = {
      'id': block.id,
      'parameterValues': block.parameterValues,
      'children': block.children.map(_blockToJson).toList(),
    };
    
    if (block.next != null) {
      json['next'] = _blockToJson(block.next!);
    }
    
    return json;
  }
  
  // 从JSON创建单个块
  static ProgramBlock _blockFromJson(Map<String, dynamic> json) {
    // 查找预定义块
    final template = ProgramBlocks.getAllBlocks().firstWhere(
      (b) => b.id == json['id'],
      orElse: () => throw Exception('未知的程序块ID: ${json['id']}'),
    );
    
    // 克隆模板并设置参数值
    final block = template.clone();
    block.parameterValues = Map<String, dynamic>.from(json['parameterValues']);
    
    // 处理子块
    if (json.containsKey('children')) {
      for (var childJson in json['children']) {
        block.children.add(_blockFromJson(childJson));
      }
    }
    
    // 处理下一个块
    if (json.containsKey('next')) {
      block.next = _blockFromJson(json['next']);
    }
    
    return block;
  }
} 